package com.bawei.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.es.service.EsDocService;
import com.bawei.system.domain.vo.EsDocInsertVo;
import com.bawei.system.domain.vo.EsDocQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class EsDocServiceImpl implements EsDocService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public R<Boolean> batchInsertDocs(List<EsDocInsertVo> esDocInsertVo) {
        BulkRequest request = new BulkRequest();
        esDocInsertVo.forEach(e -> {
            IndexRequest source = new IndexRequest(e.getIndexName()).source(JSON.toJSONString(e), XContentType.JSON);
            if (StringUtils.isNotEmpty(e.getId())) {
                source.id(e.getId());
            }
            request.add(source);
        });
        try {
            BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
            return R.ok(true, "插入成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.fail(false, "插入失败");
    }

    @Override
    public R queryDocs(EsDocQueryVo esDocInsertVo) {
        SearchRequest request = new SearchRequest(esDocInsertVo.getIndexName());
        //构建查询参数
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchAllQuery());
        //构建分页参数
        builder.from((esDocInsertVo.getPageVo().getCurrentPage() - 1) * esDocInsertVo.getPageVo().getPageSize());
        builder.size(esDocInsertVo.getPageVo().getPageSize());
        //构建排序参数
        try {
            SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            log.info("查询结果：{}", JSONObject.toJSONString(search));
            SearchHit[] hits = search.getHits().getHits();
            List<Map<String,Object>> resultData = new ArrayList<>(hits.length);
            Arrays.stream(hits).forEach(h->{
                Map<String, Object> sourceAsMap = h.getSourceAsMap();
                resultData.add(sourceAsMap);
            });
        } catch (IOException e) {
            log.error("根据条件查询es数据失败：{}", e);
        }
        return null;
    }
}
